package com.pengpeng.oauth2.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pengpeng.oauth2.constant.GatewayConstant;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import java.util.HashMap;
import java.util.List;

import lombok.extern.java.Log;
import reactor.core.publisher.Mono;

/**
 * @author LS
 * @version 1.0
 * @description: 全局过滤器
 * @date 2021/4/20 下午10:38
 */
@Configuration
@Log
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("执行全局过滤器 TokenFilter begin....");
        ServerHttpRequest request = exchange.getRequest();
        //如果是登录接口则放行
        String path = request.getPath().value();
        if (GatewayConstant.ALLOW_URL.contains(path)) {
            // 放行
            return chain.filter(exchange);
        }

        //不是登录接口则拦截 校验token
        List<String> tokens = request.getHeaders().get(GatewayConstant.AUTHORIZATION);
        if (!CollectionUtils.isEmpty(tokens)) {
            String realToken = tokens.get(0);
            if (StringUtils.hasText(realToken)) {
                // 截取  bearer xxxx
                String jwt = realToken.replaceAll("Bearer ", "");
                if (StringUtils.hasText(jwt) && redisTemplate.hasKey(GatewayConstant.TOKEN_JWT_PREFIX + jwt)) {
                    // jwt 不等空 redis也有 放行  把服务端变成有状态的 解决jwt登出问题
                    return chain.filter(exchange);
                }
            }
        }

        //token异常 返回异常json信息
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("content-type", "application/json;charset=utf-8");
        HashMap<String, String> respMap = new HashMap<>(4);
        respMap.put("code", "401");
        respMap.put("msg", "未授权");
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = null;
        try {
            bytes = objectMapper.writeValueAsBytes(respMap);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
